﻿using System.Text;
using System.Web.Mvc;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Environment.Extensions;
using Orchard.Mvc.Filters;
using Orchard.UI.Resources;
using TissotWeb.HeadFoot.Models;

namespace TissotWeb.HeadFoot.Filters {
	public class HeadFootFilter: FilterProvider, IResultFilter {
		private readonly IResourceManager _resourceManager;
		private readonly IOrchardServices _orchardServices;

        public HeadFootFilter(IResourceManager resourceManager, IOrchardServices orchardServices)
        {
			_resourceManager = resourceManager;
			_orchardServices = orchardServices;
		}

		#region IResultFilter Members

		public void OnResultExecuting(ResultExecutingContext filterContext) {
			var viewResult = filterContext.Result as ViewResult;
			if (viewResult == null)
				return;

			//Determine if we're on an admin page
			bool isAdmin = Orchard.UI.Admin.AdminFilter.IsApplied(filterContext.RequestContext);

			//Get our part data/record if available for rendering scripts
			var part = _orchardServices.WorkContext.CurrentSite.As<HeadFootSettingsPart>();
			if (part == null || (!part.IncludeInAdmin && isAdmin))
				return; // Not a valid configuration, ignore filter
			
			if (!string.IsNullOrWhiteSpace(part.Head)) {
                _resourceManager.RegisterHeadScript(part.Head);
			}
		    if (!string.IsNullOrWhiteSpace(part.Foot)) {
                _resourceManager.RegisterHeadScript(part.Foot);
		    }
		}

		public void OnResultExecuted(ResultExecutedContext filterContext) {
		}

		#endregion
	}
}